import { create } from 'zustand';
import { AppConfig, Theme, Language } from '@/types';

interface AppState extends AppConfig {
  // 操作方法
  setTheme: (theme: Theme) => void;
  setLanguage: (language: Language) => void;
  toggleSidebar: () => void;
  setCollapsed: (collapsed: boolean) => void;
}

export const useAppStore = create<AppState>((set, get) => ({
  theme: (localStorage.getItem('theme') as Theme) || 'light',
  language: (localStorage.getItem('language') as Language) || 'zh-CN',
  collapsed: localStorage.getItem('sidebarCollapsed') === 'true',

  setTheme: (theme: Theme) => {
    localStorage.setItem('theme', theme);
    set({ theme });
    
    // 更新HTML根元素的class
    if (theme === 'dark') {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  },

  setLanguage: (language: Language) => {
    localStorage.setItem('language', language);
    set({ language });
  },

  toggleSidebar: () => {
    const { collapsed } = get();
    const newCollapsed = !collapsed;
    localStorage.setItem('sidebarCollapsed', String(newCollapsed));
    set({ collapsed: newCollapsed });
  },

  setCollapsed: (collapsed: boolean) => {
    localStorage.setItem('sidebarCollapsed', String(collapsed));
    set({ collapsed });
  },
}));

// 初始化主题
const initializeTheme = () => {
  const theme = useAppStore.getState().theme;
  if (theme === 'dark') {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
};

// 应用启动时初始化
initializeTheme(); 